﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Collections.Specialized;

namespace Doo.ServerControls
{
    public class ObjectGridView : System.Web.UI.WebControls.GridView,Doo.WebUI.ILinkControl
    {
        public IOrderedDictionary ListKeys
        {
            get
            {
                IOrderedDictionary keys = ViewState["keys"] as IOrderedDictionary;
                if (keys == null)
                {
                    keys = new OrderedDictionary();
                    ViewState["keys"] = keys;
                }
                return keys;
            }
            protected set
            {
                ViewState["keys"] = value;
            }
        }

        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            base.OnSelectedIndexChanged(e);

            this.ValueChanged(this, e);
        }
        
        protected override void OnDataBinding(EventArgs e)
        {
            DataClassSource s = GetDataSource() as DataClassSource;
            s.Keys = this.ListKeys;
            s.SelectByRecord = false;

            base.OnDataBinding(e);
        }

        protected IOrderedDictionary GetDataKeys(int index)
        {
            return this.DataKeys[index].Values;
        }

        protected override void OnRowDeleting(System.Web.UI.WebControls.GridViewDeleteEventArgs e)
        {
            var view = GetData() as DataClass.DataClassView;
            view.Delete(GetDataKeys(e.RowIndex), null, new DataSourceViewOperationCallback(deleted));
        }

        protected bool deleted(int i, Exception ex)
        {
            return true;
        }

        public void ParentValueChanged(Control parent, IOrderedDictionary values)
        {
            
        }

        public event EventHandler ValueChanged;

        public IOrderedDictionary Values
        {
            get { return this.GetDataKeys(this.SelectedIndex); }
        }

        public void ChildValueChanged(Control child, IOrderedDictionary values)
        {
            RequiresDataBinding = true;
        }
    }
}
